<?php
class RatingChanger
{
    private $fileName      = '';
    private $changeCommand = '';
    private $oldRating     = '';
    private $newRating     = '';
    private $lastRecordId  = '';
    
    private function getRating()
    {
        $query = DataBaseProvider::selectRatingByFileName( $this->fileName );
        $rating = DataBase::getInstance()->query( $query );
        return $this->oldRating = intval( $rating[0]['rating'] );
    }
    
    private function putRecordToRatingLog()
    {
        $query = DataBaseProvider::insertRecordIntoRatingLog( $this->fileName, $this->changeCommand );
        if ( !DataBase::getInstance()->query( $query ) )
        {
            throw new Exception( 'record not insert' );
        }
        $this->lastRecordId = DataBase::getInstance()->getLastId();
    }
    
    private function queryFormation()
    {
        $currentRating = $this->getRating();
        
        if ( strtolower( $this->changeCommand ) == 'plus' )
        {
            $currentRating++;
            $this->changeCommand = '+1';
        }
        else if ( strtolower( $this->changeCommand ) == 'minus' )
        {
            $currentRating--;
            $this->changeCommand = '-1';
        }
        $this->newRating = $currentRating;
        $query = DataBaseProvider::updateRatingQuery( $currentRating, $this->fileName );
        return $query;
    }
    
    private function deleteLastRecord()
    {
    	$query = DataBaseProvider::deleteRatingRecord( $this->lastRecordId );
        DataBase::getInstance()->query( $query );
    }

    private function isAlreadyUpdateRating()
    {
        $query = DataBaseProvider::isAlreadyVote( $this->fileName );
        $recordId = DataBase::getInstance()->query( $query );
        if ( !empty( $recordId ) )
        {
            return true;
        }
        return false;
    }
    
    public function change( $fileName, $changeCommand )
    {
        $this->fileName      = DataBase::getInstance()->quote( $fileName );
        $this->changeCommand = DataBase::getInstance()->quote( $changeCommand );
        if ( $this->isAlreadyUpdateRating() )
        {
            throw new Exception( 'already used' );
        }
        $query = $this->queryFormation();
        $this->putRecordToRatingLog();
        if ( DataBase::getInstance()->query( $query ) )
        {
            return $this->newRating;
        }
        else
        {
            $this->deleteLastRecord();
        }
        throw new Exception( 'rating not update' );
    }
}
?>